﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Studio.DocumentDB.Dialogs
{
    /// <summary>Window displaying a spinning donut until a task finishes.</summary>
    public partial class WaitWindow : Window
    {
        /// <summary>Constructor.</summary>
        public WaitWindow()
        {
            InitializeComponent();
        }

        /// <summary>Task to await.</summary>
        public Task WaitingTask { get; set; }

        private async void Window_Activated(object sender, EventArgs e)
        {
            if (WaitingTask == null)
            {
                throw new ArgumentNullException("WaitingTask is null");
            }

            var isEnabled = Owner.IsEnabled;

            try
            {
                Owner.IsEnabled = false;

                await WaitingTask;

                DialogResult = true;
            }
            catch
            {
                DialogResult = false;
            }
            finally
            {
                Owner.IsEnabled = isEnabled;
                Close();
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (WaitingTask != null
                && !WaitingTask.IsCompleted
                && !WaitingTask.IsCanceled
                && !WaitingTask.IsFaulted)
            {
                e.Cancel = true;
            }
        }
    }
}
